package com.zipeng.service;

import com.zipeng.spring.MyApplicationContext;
import com.zipeng.spring.annotation.Component;
import com.zipeng.spring.myinterface.BeanPostProcessor;

import java.lang.reflect.Proxy;

@Component("myBeanPostProcessor")
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if(beanName.equals("userService")){
            ((UserServiceImpl)bean).setTestBeanPostProcessor("测试BeanPostProcessor");
        }
        System.out.println("初始化前，执行自定义逻辑");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化后，执行自定义逻辑");
        if("userService".equals(beanName)){
            Object proxyInstance = Proxy.newProxyInstance(MyApplicationContext.class.getClassLoader(),
                    bean.getClass().getInterfaces(), (proxy, method, args) -> {
                        System.out.println("代理逻辑");
                        return method.invoke(bean, args);
                    });
            return proxyInstance;
        }
        return bean;
    }
}